package com.itheima.reggie.controller;



import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 上传图片到本地
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {
        //判断文件夹是否存在，不存在则创建这个文件夹
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        //获得上传文件的名字
        String originalFilename = file.getOriginalFilename();
        //通过上传文件的名字获得后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //评级随机名称加后缀
        String fileName = UUID.randomUUID().toString() + suffix;
        //将文件转移到指定文件夹里
        file.transferTo(new File(basePath+fileName));
        return R.success(fileName);
    }

    /**
     * 响应图片到浏览器
     * @param name
     * @param response
     * @throws Exception
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        FileInputStream is = new FileInputStream(basePath + name);
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
        is.close();
    }
}
